<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Auto_trade extends ZhiyeAdmin_Controller {

    public function __construct(){

        parent::__construct();

		$this->load->model('auto_trade_model','auto_trade');
        $this->load->library('curl');
    }

	public function index(){
        $search["trade_way"]=$_GET['trade_way'];
        $search["create_time"]=$_GET['create_time'];
		$where=array();
		if($search["trade_way"]!=""){
			array_push($where,"trade_way like '%".$search["trade_way"]."%'");
        }
        if($search["create_time"]!=""){
			array_push($where,"create_time like '%".$search["create_time"]."%'");
		}
		if($search["submit"]==""){
			array_push($where,"auto_trade.is_delete =0");
		}
		$page_no = max(intval($page_no),1);
		$this->auto_trade->order('id DESC');
		if(count($where)>0)
			$this->auto_trade->where($where);
        $data=$this->auto_trade
						 ->select_all("auto_trade.*",null,null,true,$page_no,"auto_trade");
        $data['moudle_name']="自动交易";
        $data['table_name']="Auto_trade";

		//p($data);die();
		$data['pages']=$this->auto_trade->pages($data["total_num"]);
		$data['search']=$search;
        $this->zhiyeAdmin_view("lists", $data);		
        
    }

    public function edit($id=0){
        $data['moudle_name']="交易信息";
        $data['table_name']="Auto_trade";

		if($id>0){
			$data["auto_trade"]=$this->auto_trade->select_one($id);
        }
        $this->load->model('account_model','account');
        $res=$this->account->select_all("*",null,true,null,$page_no,"account");
        $data["account_list"]=$res["list"];
        $data["auto_trade"]["account1_id"]=26;
        $data["auto_trade"]["account2_id"]=27;
        $data["auto_trade"]["trade_way"]="btcaud";
        $this->zhiyeAdmin_view('edit',$data);
        
    }
   
    public function delete($checkIds=0){
		$checkIds=$_GET['checkIds'];
		//$str = 'apple,banana';
		$ids = explode(',', $checkIds);
		foreach ( $ids as $id )
		{
			if($id!=''){
                $this->auto_trade->delete_one($id);
			}
			echo $id;
		}
		redirect('admin/auto_trade/index');
	}
    public function orders(){
        $this->load->model('orders_model','orders');
        $trade_id=$_GET['trade_id'];

		$where=array();	
		array_push($where,"orders.is_delete =0");
        if($trade_id!=""){
            array_push($where,"trade_id =".$trade_id);
		}
		//$page_no = max(intval($page_no),1);
		$this->orders->order('id DESC');
		if(count($where)>0)
			$this->orders->where($where);
        $data=$this->orders
						 ->select_all("orders.*",null,null,null,$page_no,"orders");
		$data['moudle_name']="交易详情";
		//p($data);die();
		//$data['pages']=$this->orders->pages($data["total_num"]);

        echo json_encode($data);
        die();	
        
    }
    
    public function update($id=0){
        //获取系统值
        $this->load->model('system_setup_model','system_setup');
        $where=" where is_delete=0";
        $sql="SELECT * FROM `system_setup` ".$where;
        $data['system']=$this->system_setup->execute($sql,true,0);
        foreach (json_decode(json_encode($data['system'])) as $system )
        {
            $system_setup[$system->remarks.'_system']=$system->key_value;
        }
        // echo $system_setup['appid_system'];
        // echo $system_setup['otp_code_system'];
        // echo $system_setup['sessions_url_system'];
        // echo $system_setup['api_url_system'];
        // die();

        $auto_trade=$this->input->post('auto_trade');
        // $appid="89951420b05b4a63865da182496babdcb45f00c5af93491cba2638c22c6fb3ef";
        // $otp_code="663925";
        $appid=$system_setup['appid_system'];
        $otp_code=$system_setup['otp_code_system'];
        $this->load->model('account_model','account');
        $this->load->model('balance_model','balance');
		if($id>0){
			$this->auto_trade->update($auto_trade, array('id='.$id));
		}else{      
            // get account1 sessions   
            $data["account1"]=$this->account->select_one($auto_trade['account1_id']);
            $account1_email=$data["account1"]["account"];
            $account1_password=$data["account1"]["account_password"];
            $url = $system_setup['sessions_url_system']."sessions?email=$account1_email&password=$account1_password&application_id=$appid&otp_code=$otp_code";
            $account1_sessions=$this->curl->ssl()->simple_post($url);
            $account1_sessions=str_replace("\"","",$account1_sessions);

            // get account2 sessions
            $data["account2"]=$this->account->select_one($auto_trade['account2_id']);
            $account2_email=$data["account2"]["account"];
            $account2_password=$data["account2"]["account_password"];
            $url = $system_setup['sessions_url_system']."sessions?email=$account2_email&password=$account2_password&application_id=$appid&otp_code=$otp_code";
            $account2_sessions=$this->curl->ssl()->simple_post($url);
            $account2_sessions=str_replace("\"","",$account2_sessions);

            $headers1=array(
                "Authorization"=>" Bearer $account1_sessions",
            );
            $headers2=array(
                "Authorization"=>" Bearer $account2_sessions",
            );

            //get accounts1
            $url=$system_setup['api_url_system']."accounts";
            $accounts1=$this->curl->ssl()->http_header($headers1)->simple_get($url);            
            //修改表account数据
            $accounts= json_decode($accounts1,false);
            foreach ($accounts as $item) {
                $account1[$item->currency.'_balance']=$item->balance;
            }
            $account1['token']=$account1_sessions;
            $this->account->update($account1, array('id='.$auto_trade['account1_id']));

            //添加表balance数据
            $balance['account']=$account1_email;
            $balance['account_id']=$auto_trade['account1_id'];
            foreach ($accounts as $item) {
                $balance[$item->currency.'_balance']=$item->balance;
                $balance[$item->currency.'_locked']=$item->locked;
            }
            $this->balance->insert($balance);
            
            //get accounts2
            $url=$system_setup['api_url_system']."accounts";
            $accounts2=$this->curl->ssl()->http_header($headers2)->simple_get($url);            
            //修改表account数据
            $accounts= json_decode($accounts2,false);
            foreach ($accounts as $item) {
                $account2[$item->currency.'_balance']=$item->balance;
            }
            $account2['token']=$account2_sessions;
            $this->account->update($account2, array('id='.$auto_trade['account2_id']));
            
            //添加表balance数据
            $balance['account']=$account2_email;
            $balance['account_id']=$auto_trade['account2_id'];
            foreach ($accounts as $item) {
                $balance[$item->currency.'_balance']=$item->balance;
                $balance[$item->currency.'_locked']=$item->locked;
            }
            $this->balance->insert($balance);

            $auto_trade['account1']=$account1_email;
            $auto_trade['account2']=$account2_email;
			$trade_id=$this->auto_trade->insert($auto_trade);

            for($i=0;$i<$auto_trade['trade_num'];$i++){
                $this->order_post($system_setup['api_url_system'],$trade_id,$auto_trade['trade_way'],$auto_trade['account1_id'],$auto_trade['account2_id'],$headers1,$headers2); 
            }

		}
		redirect('auto_trade/auto_trade/index');
    }
    public function add(){
        //获取系统值
        $this->load->model('system_setup_model','system_setup');
        $where=" where is_delete=0";
        $sql="SELECT * FROM `system_setup` ".$where;
        $data['system']=$this->system_setup->execute($sql,true,0);
        foreach (json_decode(json_encode($data['system'])) as $system )
        {
            $system_setup[$system->remarks.'_system']=$system->key_value;
        }
        // echo $system_setup['appid_system'];
        // echo $system_setup['otp_code_system'];
        // echo $system_setup['sessions_url_system'];
        // echo $system_setup['api_url_system'];
        $appid=$system_setup['appid_system'];
        $otp_code=$system_setup['otp_code_system'];
        
        $account1_id=$_GET['account1_id'];
        $account2_id=$_GET['account2_id'];
        $trade_way=$_GET['trade_way'];
        $trade_num=$_GET['trade_num'];
       
        $this->load->model('account_model','account');
        $this->load->model('balance_model','balance');
        
        // get account1 sessions   
        $data["account1"]=$this->account->select_one($account1_id);
        $account1_email=$data["account1"]["account"];
        $account1_password=$data["account1"]["account_password"];
        $url = $system_setup['sessions_url_system']."sessions?email=$account1_email&password=$account1_password&application_id=$appid&otp_code=$otp_code";
        $account1_sessions=$this->curl->ssl()->simple_post($url);
        $account1_sessions=str_replace("\"","",$account1_sessions);

        // get account2 sessions
        $data["account2"]=$this->account->select_one($account2_id);
        $account2_email=$data["account2"]["account"];
        $account2_password=$data["account2"]["account_password"];
        $url = $system_setup['sessions_url_system']."sessions?email=$account2_email&password=$account2_password&application_id=$appid&otp_code=$otp_code";
        $account2_sessions=$this->curl->ssl()->simple_post($url);
        $account2_sessions=str_replace("\"","",$account2_sessions);

        $headers1=array(
            "Authorization"=>" Bearer $account1_sessions",
        );
        $headers2=array(
            "Authorization"=>" Bearer $account2_sessions",
        );

        //get accounts1
        $url=$system_setup['api_url_system']."accounts";
        $accounts1=$this->curl->ssl()->http_header($headers1)->simple_get($url);            
        //修改表account数据
        $accounts= json_decode($accounts1,false);
        foreach ($accounts as $item) {
            $account1[$item->currency.'_balance']=$item->balance;
        }
        $account1['token']=$account1_sessions;
        $this->account->update($account1, array('id='.$account1_id));

        //添加表balance数据
        $balance['account']=$account1_email;
        $balance['account_id']=$account1_id;
        foreach ($accounts as $item) {
            $balance[$item->currency.'_balance']=$item->balance;
            $balance[$item->currency.'_locked']=$item->locked;
        }
        $this->balance->insert($balance);
        
        //get accounts2
        $url=$system_setup['api_url_system']."accounts";
        $accounts2=$this->curl->ssl()->http_header($headers2)->simple_get($url);            
        //修改表account数据
        $accounts= json_decode($accounts2,false);
        foreach ($accounts as $item) {
            $account2[$item->currency.'_balance']=$item->balance;
        }
        $account2['token']=$account2_sessions;
        $this->account->update($account2, array('id='.$account2_id));
        
        //添加表balance数据
        $balance['account']=$account2_email;
        $balance['account_id']=$account2_id;
        foreach ($accounts as $item) {
            $balance[$item->currency.'_balance']=$item->balance;
            $balance[$item->currency.'_locked']=$item->locked;
        }
        $this->balance->insert($balance);

        $auto_trade['account1']=$account1_email;
        $auto_trade['account1_id']=$account1_id;
        $auto_trade['account2']=$account2_email;
        $auto_trade['account2_id']=$account2_id;
        $auto_trade['trade_way']=$trade_way;
        $auto_trade['trade_num']=$trade_num;
        $trade_id=$this->auto_trade->insert($auto_trade);

        for($i=0;$i<$auto_trade['trade_num'];$i++){
            $this->order_post($system_setup['api_url_system'],$trade_id,$auto_trade['trade_way'],$auto_trade['account1_id'],$auto_trade['account2_id'],$headers1,$headers2); 
        }
        $this->order_trades(); 
        die();
		//redirect('auto_trade/auto_trade/index');
	}
    public function order_post($api_url_system,$trade_id,$market,$account1_id,$account2_id,$headers1,$headers2){
		//get order_book
		$url=$api_url_system."order_book?market=$market&bids_limit=1&asks_limit=1";
		$order_book=$this->curl->ssl()->http_header($headers2)->simple_get($url);
		$order_book=json_decode($order_book,false);
		//get the middle price
		$buy=$order_book->bids[0]->price;
		$sell=$order_book->asks[0]->price;
		$price_rand=mt_rand(1,9)/10;
		$my_price=$buy+($sell-$buy)*$price_rand;
	    /*
		如果没有订单得话 这个价格怎么定	
		if($my_price==0){
			$my_price=8872.5;
		}*/
		//数量不要超过1
		$volume=mt_rand(1,9)/10;
		//create account1 sell order
		$url=$api_url_system."orders";
		$post_data=array(
			"market"=>$market,
			"side"=>"sell",
			"volume"=>$volume,
			"price"=>$my_price
		);
		$create_sell_order=$this->curl->ssl()->http_header($headers1)->simple_post($url, $post_data);
        $this->insert_orders($api_url_system,$create_sell_order,$headers1,$account1_id,$trade_id);		                                     

		//create account2 buy order
		$url=$api_url_system."orders";
		$post_data=array(
			"market"=>$market,
			"side"=>"buy",
			"volume"=>$volume,
			"price"=>$my_price
		);
		$create_buy_order=$this->curl->ssl()->http_header($headers2)->simple_post($url, $post_data);
        $this->insert_orders($api_url_system,$create_buy_order,$headers2,$account2_id,$trade_id);		                                     

		//create account2 sell order
		$url=$api_url_system."orders";
		$post_data=array(
			"market"=>$market,
			"side"=>"sell",
			"volume"=>$volume,
			"price"=>$my_price
		);
		$create_sell_order=$this->curl->ssl()->http_header($headers2)->simple_post($url, $post_data);
        $this->insert_orders($api_url_system,$create_sell_order,$headers2,$account2_id,$trade_id);		                                     

		//create account1 buy order
		$url=$api_url_system."orders";
		$post_data=array(
			"market"=>$market,
			"side"=>"buy",
			"volume"=>$volume,
			"price"=>$my_price
		);
        $create_buy_order=$this->curl->ssl()->http_header($headers1)->simple_post($url, $post_data);
        
        $this->insert_orders($api_url_system,$create_buy_order,$headers1,$account1_id,$trade_id);		                                     

    }
    //,$headers,$account
    public function insert_orders($api_url_system,$create_order,$headers,$account_id,$trade_id){
        //存入数据库 表orders
        $this->load->model('orders_model','orders');
        $data["account"]=$this->account->select_one($account_id);
        $orders['order_id']=json_decode($create_order)->id;
        $orders['trade_id']=$trade_id;
        $orders['account_id']=$account_id;
        $orders['account']=$data["account"]["account"];
        $orders['side']=json_decode($create_order)->side;
        $orders['ord_type']=json_decode($create_order)->ord_type;
        $orders['price']=json_decode($create_order)->price;
        $orders['avg_price']=json_decode($create_order)->avg_price;
        $orders['state']=json_decode($create_order)->state;
        $orders['market']=json_decode($create_order)->market;
        $orders['created_at']=json_decode($create_order)->created_at;
        $orders['volume']=json_decode($create_order)->volume;
        $orders['remaining_volume']=json_decode($create_order)->remaining_volume;
        $orders['executed_volume']=json_decode($create_order)->executed_volume;
        $orders['trades_count']=json_decode($create_order)->trades_count;
        $i=$this->orders->insert($orders);

        //update order trades
        $url=$api_url_system."order?id=".json_decode($create_order)->id;
        //echo $url;
        $order_trades=$this->curl->ssl()->http_header($headers)->simple_get($url);
        //echo $order_trades;
        $orders['remarks']=json_encode(json_decode($order_trades)->trades);   
       // echo $orders['remarks'];
        $i=$this->orders->update($orders, array('id='.$i)); 
    }
    public function order_trades(){
		//获取系统值
        $this->load->model('system_setup_model','system_setup');
        $where=" where is_delete=0";
        $sql="SELECT * FROM `system_setup` ".$where;
        $data['system']=$this->system_setup->execute($sql,true,0);
        foreach (json_decode(json_encode($data['system'])) as $system )
        {
            $system_setup[$system->remarks.'_system']=$system->key_value;
        }
        $appid=$system_setup['appid_system'];
        $otp_code=$system_setup['otp_code_system'];
		 // get account1 sessions   
		 $account1_email='test1@sccx.exchange';
		 $account1_password='Welcome111';
		 $url = $system_setup['sessions_url_system']."sessions?email=$account1_email&password=$account1_password&application_id=$appid&otp_code=$otp_code";
		 $account1_sessions=$this->curl->ssl()->simple_post($url);
		 $account1_sessions=str_replace("\"","",$account1_sessions);
 
		 $headers1=array(
			 "Authorization"=>" Bearer $account1_sessions",
		 );
		 echo json_encode($headers1)."<hr />";


		  // get account1 sessions   
		  $account2_email='test2@sccx.exchange';
		  $account2_password='Welcome222';
		  $url = $system_setup['sessions_url_system']."sessions?email=$account2_email&password=$account2_password&application_id=$appid&otp_code=$otp_code";
		  $account2_sessions=$this->curl->ssl()->simple_post($url);
		  $account2_sessions=str_replace("\"","",$account2_sessions);
  
		  $headers2=array(
			  "Authorization"=>" Bearer $account2_sessions",
		  );
		  echo json_encode($headers2)."<hr />";

		$this->load->model('orders_model','orders');
        $sql="SELECT a.id, a.order_id, a.account,b.account_password,a.side,a.remarks FROM `orders` a,account b WHERE a.remarks='[]' AND a.account=b.account ";
		$data['orders']=$this->orders->execute($sql,true,0);
		foreach (json_decode(json_encode($data['orders'])) as $order) {
			 //update order trades
			 $url=$system_setup['api_url_system']."order?id=".$order->order_id;
			 if($order->account=='test1@sccx.exchange'){
				$order_trades=$this->curl->ssl()->http_header($headers1)->simple_get($url);
				echo $order_trades."<hr />";
			 }else{
				$order_trades=$this->curl->ssl()->http_header($headers2)->simple_get($url);
				echo $order_trades."<hr />";
			 }
			 $orders['remarks']=json_encode(json_decode($order_trades)->trades);   
			 echo $orders['remarks']."<hr />";

			 $i=$this->orders->update($orders, array('id='.$order->id)); 
		}
		die();
		
	}
}